import base64

from django.core.files.base import ContentFile
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSetMixin
from rest_framework_jwt.utils import jwt_decode_handler

from bigevent_admin.serializers import users
from rest_framework.generics import RetrieveUpdateAPIView,CreateAPIView, UpdateAPIView

from bigevent_admin.serializers.users import UserSerializer, UserImageSerializer
from users.models import User, UserImage


#用户注册
from utils.jwt_utils import get_user


class UserView(CreateAPIView):

    serializer_class = UserSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response({
                          "status": 0,
                          "message": "注册成功！"
                        })


class UserInfoView(RetrieveUpdateAPIView):
    # permission_classes = [IsAuthenticated]
    serializer_class = UserSerializer
    queryset = User.objects.all()
    # def get_object(self):
    # #     #前端路由信息未携带用户信息  暂时固定返回测试用户信息
    # #     user = User.objects.get(id = 13)
    # #     return user
    # def get_object(self):
    #     # 前端路由信息未携带用户信息  暂时返回测试用户信息
    #     user = User.objects.get(id=13)
    #     return user
    def get_object(self,request):
        # 前端路由信息未携带用户信息  通过token获取用户信息
        header_token = request.META.get("HTTP_AUTHORIZATION")
        token = header_token.split(' ', 1)[1]
        username = jwt_decode_handler(token).get('username')
        user = User.objects.get(username=username)
        return user


    def retrieve(self, request, *args, **kwargs):

        user = self.get_object(request)
        ser = self.get_serializer(user)
        return Response(
            {
                "status": 0,
                "message": "获取用户基本信息成功！",
                "data": ser.data
            }

        )

    def post(self,request,*args, **kwargs):
        '''
        :param request: 更新用户信息，部分
        :param args:
        :param kwargs:
        :return:
        '''
        user = self.get_object(request)
        user.email = request.data.get('email')
        user.nickname = request.data.get('nickname')
        user.username = request.data.get('username')
        user.save()
        return Response({
            "status": 0,
            "message": "修改用户信息成功！"
        })
    def updatepwd(self,request):
        user = self.get_object(request)
        data = request.data


class UserUpdatePwdView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserSerializer
    queryset = User.objects.all()
    # def get_object(self):
    # #     #前端路由信息未携带用户信息  暂时固定返回测试用户信息
    # #     user = User.objects.get(id = 13)
    # #     return user
    # def get_object(self):
    #     # 前端路由信息未携带用户信息  暂时返回测试用户信息
    #     user = User.objects.get(id=13)
    #     return user
    def get_object(self,request):
        # 前端路由信息未携带用户信息  通过token获取用户信息
        user = get_user(request)
        return user

    def post(self,request,*args, **kwargs):
        '''
        :param request: 更新用户信息，部分
        :param args:
        :param kwargs:
        :return:
        '''
        user = self.get_object(request)
        oldPwd = request.data.get('oldPwd')
        newPwd = request.data.get('newPwd')
        if not user.check_password(oldPwd):
            return Response({
                "status": 1,
                "message": "更新密码失败！"
            })

        user.set_password(newPwd)
        user.save()
        return Response({
                          "status": 0,
                          "message": "更新密码成功！"
                        })


class UserUpdateImgView(APIView):
    # permission_classes = [IsAuthenticated]
    # serializer_class = UserImageSerializer
    # queryset = UserImage.objects.all()
    def post(self, request, *args, **kwargs):
        user = get_user(request)
        try:
            _img = UserImage.objects.get(user=user)
        except Exception as e:
            print(e)
            _img = None
        file_base64 = request.data.get('avatar').split('base64,',1).pop()
        file_data = base64.b64decode(file_base64)
        f = ContentFile(file_data,'头像.jpg')
        data={
            'user':user.id,
            'cover_img':f
        }
        # img = UserImage.objects.create(user=user,cover_img=f)
        # img.save()
        ser = UserImageSerializer(_img,data=data)
        ser.is_valid()
        ser.save()
        print('成功')
        return Response({
                          "status": 0,
                          "message": "更新头像成功！"
                        })

